package core.buffer;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class BufferManager {

    private HashMap<Integer, List<Buffer>> _buffers = new HashMap<>();

    public synchronized Buffer apply(int size) {

        if (!_buffers.containsKey(size)) {
            _buffers.put(size, new ArrayList<>());
        }
        Buffer buffer = null;
        List<Buffer> buffers = _buffers.get(size);
        for (Buffer byteBuffer : buffers) {
            if (byteBuffer.readRemaining() == 0 && byteBuffer.dirty()) {
                buffer = byteBuffer;
                buffer.clear();
                break;
            }
        }
        if (buffer == null) {
            buffer = new Buffer(size);
            buffers.add(buffer);
        }
        return buffer;
    }

}
